package gps;

import gps.api.GPSProblem;
import gps.implementationAPI.GPSProblemImplementation;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

public class GPSRun {
	private static final Logger LOGGER = Logger.getLogger(GPSRun.class);
	public static final Integer N = 3;
	
	public static void main(String[] args) {
		if (args.length == 0) {
			LOGGER.error("No configuration file!");
			return;
		}
		Properties prop = new Properties();
	    String fileName = args[0];
	    InputStream is = null;
		try {
			is = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			LOGGER.error("¡File: " + fileName + " doesn't exist!");
			System.exit(1);
		}

	    try {
			prop.load(is);
		} catch (IOException e) {
			LOGGER.error("Cannot load configuration's file properties!");
			System.exit(1);
		}
		
		SearchStrategy searchStrategy = assignSearchStrategy(prop.getProperty("searchStrategy"));
		if (searchStrategy == null) {
			LOGGER.error("Invalid Search Strategy!");
			System.exit(1);
		}
		LOGGER.info("Search Strategy: " + searchStrategy.toString());
		GPSProblem gpsProblem = assignHeuristic(prop.getProperty("heuristics"));
		if (gpsProblem == null) {
			LOGGER.error("Invalid Heuristic!");
			System.exit(1);
		}
		Long initialTime = System.currentTimeMillis();
		GPSEngine.engine(gpsProblem, searchStrategy);
		System.out.println("Total time: " + ((System.currentTimeMillis() - initialTime)/1000) + " seconds");
	}

	private static SearchStrategy assignSearchStrategy(String searchStrategy) {
		if (searchStrategy == null) {
			return null;
		}
		if (searchStrategy.toUpperCase().equals("DFS")) {
			return SearchStrategy.DFS;
		} else if (searchStrategy.toUpperCase().equals("BFS")) {
			return SearchStrategy.BFS;
		} else if (searchStrategy.toUpperCase().equals("ASTAR")) {
			return SearchStrategy.AStar;
		} else if (searchStrategy.toUpperCase().equals("PI")) {
			return SearchStrategy.PI;
		} else if (searchStrategy.toUpperCase().equals("GS")) {
			return SearchStrategy.GS;
		}
		return null;
	}
	
	private static GPSProblem assignHeuristic(String heuristic) {
		if (heuristic == null) {
			return null;
		}
		if (heuristic.toLowerCase().equals("heuristic1")) {
			return new GPSProblemImplementation();
		}
		return null;
	}
}
